/*
 * @Author: caiqi
 * @Date: 2019-02-14 14:34:34
 * @Last Modified by: cai.qi
 * @Last Modified time: 2020-01-08 14:03:30
 * @Describe:
 */

"use strict";

import { Service } from "egg";

export default class TypeService extends Service {
    // ======================================================================  注册/更新  ======================================================================
    async register(body) {
        const { ctx } = this;
        body.username = ctx.helper.shtml(body.username);
        body.mobile = parseInt(body.mobile)
        body.password = await ctx.genHash(body.password);
        // 判断账号是否已注册
        const chickuser = await ctx.model.ModAdmin.findOne({ where: { username: body.username, status: 1 } });
        if (chickuser && chickuser.username === body.username) {
            ctx.throw('当前账号已注册', 201);
        }
        const user = await ctx.model.ModAdmin.create(body);
        return {
            token: await ctx.service.sevCommon.admin(user.id),
            user: {
                user_id: user.id,
                user_name: user.username,
                user_mobile: user.mobile
            },
        };
    }
    // ------------------------------ 登录
    async login(body) {
        const { ctx } = this;
        let user = await ctx.model.ModAdmin.findOne({ where: { username: body.username } });
        if (!user) {
            ctx.throw('请输入正确的账号', 201);
        }
        const verifyPsw = await ctx.compare(body.password, user.password);
        if (!verifyPsw) {
            ctx.throw('账号或密码错误', 201);
        }
        user = JSON.parse(JSON.stringify(user));
        return {
            token: await ctx.service.sevCommon.admin(user),
            user: {
                user_id: user.id,
                user_name: user.username,
                user_mobile: user.mobile
            },
        };
    }
}
